﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using CSM.Controllers;
using CSM.Models;
using System.Text;

namespace CSM.Views.Wenjuan
{
    public partial class QuestionBase : System.Web.UI.Page
    {
        CustomDataContext db = new CustomDataContext();
        public string alert;
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {

                BindMyData(0, "");
                int Totals = TotalPageAmount("");
                int pages = (Totals % 10) == 0 ? (Totals / 10) : (Totals / 10 + 1);
                Label_Total.Text = "共" + pages.ToString();
                Label_CurrenPageAndTo.Text = "页，当前第1" + " 页，转到";
                EditFlag.Value = "add";
            }
        }
        #region 绑定数据及翻页
        private void BindMyData(int PageIndex, string starts)
        {
            int skipAccount = PageIndex * 10;
            var MyQuery = (from a in db.TCrm_WJ_QuestionBase
                           where a.Title.Contains(starts)
                           select new
                           {
                               a.QuestionID,
                               Qtype = a.QType == '0' ? "选择题" : "简答题",
                               a.Title,
                           }).Skip(skipAccount).Take(10);
            GridView_Users.DataSource = MyQuery;
            GridView_Users.DataBind();


        }

        //查询出当前记录信息的总条数。
        private int TotalPageAmount(string starts)
        {
            int MyQuery = 0;
            MyQuery = (from a in db.TCrm_WJ_QuestionBase where a.QuestionID.StartsWith(starts) select a).Count();
            return MyQuery;
        }


        //点击按钮，执行查询
        protected void MyClick(object sender, EventArgs e)
        {


            int pageIndx = Convert.ToInt32(CurrentPage.Value);
            string starts = txtUser.Text;
            int Totals = TotalPageAmount(starts);
            int pages = (Totals % 10) == 0 ? (Totals / 10) : (Totals / 10 + 1);

            Label_Total.Text = "共" + pages.ToString();

            if (typeof(Button).IsInstanceOfType(sender))
            {
                string arg = ((Button)sender).CommandArgument.ToString().ToLower();

                switch (arg)
                {
                    case "first":

                        pageIndx = 0;

                        break;
                    case "gotopage":
                        if (TextBox_PageIndex.Text == "")
                        { pageIndx = 0; }
                        else
                        {
                            int xx = Convert.ToInt32(TextBox_PageIndex.Text);
                            if (xx > pages)
                            { pageIndx = pages - 1; }

                            else
                            { pageIndx = xx - 1; }


                        }
                        break;
                }

            }
            else if (typeof(LinkButton).IsInstanceOfType(sender))
            {

                string arg = ((LinkButton)sender).CommandArgument.ToString().ToLower();

                switch (arg)
                {
                    case "prev":
                        if (pageIndx > 0)
                        {
                            pageIndx = pageIndx - 1;
                        }
                        break;
                    case "next":
                        if (pageIndx < pages - 1)
                        {
                            pageIndx = pageIndx + 1;
                        }
                        break;
                    case "last":
                        pageIndx = pages - 1;
                        break;
                    case "first":
                        pageIndx = 0;
                        break;
                }

            }

            CurrentPage.Value = pageIndx.ToString();  //对保存页码状态信息的隐藏字段进行赋值。保存当前页码。
            Label_CurrenPageAndTo.Text = "页，当前第" + (pageIndx + 1).ToString() + " 页，转到";

            BindMyData(pageIndx, starts);

        }

        #endregion
        //取消的按钮
        protected void Button_Cancel_Command(object sender, CommandEventArgs e)
        {
            EditFlag.Value = "0";
            Panel_Edit.Visible = false;
            Panel_Gridlist.Visible = true;
            if (EditFlag.Value == "edit")
            {
                TextBox_QId.Enabled = true;
            }

        }

        //增加按钮的事件
        protected void Button_Add_Command(object sender, CommandEventArgs e)
        {
            //清空
            Panel_Gridlist.Visible = false;
            TextBox_QId.Text = "";
            TextBox_Content.Text = "";
            CheckBox_QuesType.Checked = false;
            Panel_Edit.Visible = true;
            TextBox_QId.Enabled = true;
            EditFlag.Value = "add";
            ScriptManager.RegisterStartupScript((System.Web.UI.Page)HttpContext.Current.CurrentHandler, typeof(System.Web.UI.Page), "addtext", "<script>ShowThickBox('增加','Panel_Edit');</script>", false);
        }

        //保存的按钮
        protected void Button_Save_Command(object sender, CommandEventArgs e)
        {

            //根据当前的编辑状态来判断，是增加还是编辑
            if (EditFlag.Value == "add")
            {
                string QuestId = TextBox_QId.Text;
                if (QuestId == "")
                {
                    Page.ClientScript.RegisterClientScriptBlock(Page.GetType(), "message", " <script>alert('题目ID不允许为空值。'); </script>");
                    ScriptManager.RegisterStartupScript((System.Web.UI.Page)HttpContext.Current.CurrentHandler, typeof(System.Web.UI.Page), "addtext", "<script>ShowThickBox('编辑','Panel_Edit');</script>", false);
                    return;

                }
                var IsExist = from a in db.TCrm_WJ_QuestionBase
                              where a.QuestionID == QuestId
                              select a;
                if (IsExist.Count() != 0)
                {
                    Page.ClientScript.RegisterClientScriptBlock(Page.GetType(), "message", " <script>alert('当前题目ID已存在。'); </script>");
                    ScriptManager.RegisterStartupScript((System.Web.UI.Page)HttpContext.Current.CurrentHandler, typeof(System.Web.UI.Page), "addtext", "<script>ShowThickBox('编辑','Panel_Edit');</script>", false);
                    return;
                }
                TCrm_WJ_QuestionBase myrow = new TCrm_WJ_QuestionBase();
                myrow.QuestionID = TextBox_QId.Text;
                myrow.Title = TextBox_Content.Text;
                myrow.QType = (CheckBox_QuesType.Checked == true ? '1' : '0');
                db.TCrm_WJ_QuestionBase.InsertOnSubmit(myrow);
                db.SubmitChanges();
                for (int j = 1; j < Convert.ToInt32(OptionNum.Value) + 1; j++)
                {
                    TCrm_WJ_QuestionBase_Detail mydetailrow = new TCrm_WJ_QuestionBase_Detail();
                    mydetailrow.OptionID = j.ToString();
                    string a = Request.Form.Get("Txt_Option" + (j - 1).ToString());
                    mydetailrow.OptionLabel = Request.Form.Get("Txt_Option" + (j - 1).ToString()) == null ? "" : Request.Form.Get("Txt_Option" + (j - 1).ToString());
                    mydetailrow.QuestionID = TextBox_QId.Text;
                    db.TCrm_WJ_QuestionBase_Detail.InsertOnSubmit(mydetailrow);
                    db.SubmitChanges();
                }


            }
            else if (EditFlag.Value == "edit")
            {
                string QuestId = TextBox_QId.Text;
                var myEditQuery = (from a in db.TCrm_WJ_QuestionBase where a.QuestionID == QuestId select a).Single();
                myEditQuery.QuestionID = QuestId;
                myEditQuery.Title = TextBox_Content.Text;
                myEditQuery.QType = (CheckBox_QuesType.Checked == true ? '1' : '0');
                db.SubmitChanges();
                var queryDel = from a in db.TCrm_WJ_QuestionBase_Detail where a.QuestionID == QuestId select a;
                db.TCrm_WJ_QuestionBase_Detail.DeleteAllOnSubmit(queryDel);
                db.SubmitChanges();
                for (int j = 1; j < Convert.ToInt32(OptionNum.Value) + 1; j++)
                {
                    TCrm_WJ_QuestionBase_Detail mydetailrow = new TCrm_WJ_QuestionBase_Detail();
                    mydetailrow.QuestionID = QuestId;
                    mydetailrow.OptionID = j.ToString();
                    mydetailrow.OptionLabel = Request.Form.Get("Txt_Option" + (j - 1).ToString()) == null ? "" : Request.Form.Get("Txt_Option" + (j - 1).ToString());
                    db.TCrm_WJ_QuestionBase_Detail.InsertOnSubmit(mydetailrow);
                    db.SubmitChanges();
                }

            }
            OptionNum.Value = "1";
            Page.ClientScript.RegisterClientScriptBlock(Page.GetType(), "message", " <script>closewind(); </script>");
            EditFlag.Value = "0";
            Panel_Edit.Visible = false;
            Panel_Gridlist.Visible = true;
            int PageIndex = Convert.ToInt32(CurrentPage.Value);
            string user = txtUser.Text;
            BindMyData(PageIndex, user);
        }
        protected void Button_Delete_Command(object sender, CommandEventArgs e)
        {
            string myid = e.CommandArgument.ToString();
            var query = from a in db.TCrm_WJ_CustomerAnswer where a.QuestionID == myid select a;
            if (query.Count() == 0)
            {
                var query2 = from a in db.TCrm_WJ_Statistics_Detail where a.QuestionID==myid && a.QuestionID != null select a;
                if (query2.Count() != 0)
                {
                    alert = "<script>alert('有问卷包含该题，请先在该问卷中删除该题');</script>";
                }
                else
                {
                    var MyQuery = from a in db.TCrm_WJ_QuestionBase
                                  where a.QuestionID == myid
                                  select a;
                    var Myquery2 = from a in db.TCrm_WJ_QuestionBase_Detail where a.QuestionID == myid select a;
                    //以前保存的数据删除
                    db.TCrm_WJ_QuestionBase.DeleteAllOnSubmit(MyQuery);
                    db.SubmitChanges();
                    db.TCrm_WJ_QuestionBase_Detail.DeleteAllOnSubmit(Myquery2);
                    db.SubmitChanges();
                    alert = "<script>alert('删除成功');</script>";
                    BindMyData(0, "");
                }
            }
            else
            {
                alert = "<script>alert('存在该题结果，请先删除该题结果');</script>";
            }
        }
        //编辑
        protected void Button_Edit_Command(object sender, CommandEventArgs e)
        {
            string myid = e.CommandArgument.ToString();
            //yang  题目与选项构成主从表关系。应使用左联接查询，以避免选项空值产生。
            var query3 = from a in db.TCrm_WJ_Statistics_Detail where a.QuestionID==myid select a;
            if (query3.Count() != 0)
            {
                alert = "<script>alert('当前题目存在问卷中，不能编辑');</script>";
            }
            var myEditQuery = from a in db.TCrm_WJ_QuestionBase
                              join b in db.TCrm_WJ_QuestionBase_Detail on a.QuestionID equals b.QuestionID
                              into temps
                              from temp in temps.DefaultIfEmpty()
                              where a.QuestionID == myid
                              select new
                              {
                                  a.QuestionID,
                                  a.QType,
                                  a.Title,
                                  OptionID = (temp.OptionID == null ? "" : temp.OptionID),
                                  OptionLabel = (temp.OptionLabel == null ? "" : temp.OptionLabel)
                              };
            TextBox_QId.Text = myEditQuery.First().QuestionID;
            TextBox_Content.Text = myEditQuery.First().Title;
            CheckBox_QuesType.Checked = myEditQuery.First().QType == '0' ? false : true;
            TextBox_QId.Enabled = false;
            EditFlag.Value = "edit";
            Panel_Edit.Visible = true;
            Panel_Gridlist.Visible = false;
            int i = 0;
            string str = "";
            //根据选项条数，
            foreach (var a in myEditQuery)
            {
                int k = i + 1;
                str += "<tr><td class='tdClass'>选项" + k + ":</td>";
                str += "<td class='tdClass'><input name='Txt_Option" + i + "' id='Txt_Option" + i + "' value='" + a.OptionLabel + "' type='text'/></td></tr>";
                i++;
            }
            OptionNum.Value = i.ToString();
            stringa.Value = str;
            ScriptManager.RegisterStartupScript((System.Web.UI.Page)HttpContext.Current.CurrentHandler, typeof(System.Web.UI.Page), "add", "<script>addrow();</script>", false);
            ScriptManager.RegisterStartupScript((System.Web.UI.Page)HttpContext.Current.CurrentHandler, typeof(System.Web.UI.Page), "addtext", "<script>ShowThickBox('编辑','Panel_Edit');</script>", false);
        }

        protected void Button_Browse_Click(object sender, EventArgs e)
        {
            //根据筛选条件，查询
            string user = txtUser.Text;
            BindMyData(0, user);
        }

    }
}
